const connection = require("../app/database");

class SupportService {

  // 是否点赞
  async isSupport(tableName, resourceId, userId) {
    try {
      const statement = `SELECT ${tableName}_id, user_id FROM ${tableName}_support WHERE ${tableName}_id = ? AND user_id = ?`;
      const result = await connection.execute(statement, [resourceId, userId]);
      return result[0].length === 0 ? false : true;
    } catch (error) {
      console.log(error);
    }
  }

  // 点赞操作
  async toSupport(tableName, resourceId, userId) {
    try {
      // 操作点赞表
      const statement1 = `INSERT INTO ${tableName}_support (${tableName}_id, user_id) values(?, ?)`;
      // 操作动态表
      const statement2 = `UPDATE ${tableName} SET likes = likes + 1 where id = ?`;
      // 执行语句
      await connection.execute(statement1, [resourceId, userId]);
      await connection.execute(statement2, [resourceId]);
      // 返回结果
      return {
        isSupport: true
      }
    } catch (error) {
      console.log(error);
    }
  }

  // 取消点赞操作
  async unSupport(tableName, resourceId, userId) {
    try {
      // 操作点赞表
      const statement1 = `DELETE FROM ${tableName}_support WHERE ${tableName}_id = ? AND user_id = ?`;
      // 操作动态表
      const statement2 = `UPDATE ${tableName} SET likes = likes - 1 where id = ?`;
      // 执行语句
      await connection.execute(statement1, [resourceId, userId]);
      await connection.execute(statement2, [resourceId]);
      // 返回结果
      return {
        isSupport: false
      }
    } catch (error) {
      console.log(error);
    }
  }

}

module.exports = new SupportService();
